<script setup lang="ts">
  const formRef = ref()
  const rPasswordFormItemRef = ref()
  const nuxtApp = useNuxtApp()
  const route = useRoute()
  const showDispatchModalRef = ref(false)

  const { key, type } = route.query

  // 要提交到后端的数据
  const verifyForm = ref({
    password: null,
    confirmPassword: null,
    key,
    type
  })
  const registerLoading = ref(false)

  // 数据验证
  function validateConfirmPasswordStartWith (
    rule,
    value
  ) {
    const modelRef = verifyForm.value
    return (
      !!modelRef.password &&
      modelRef.password.startsWith(value) &&
      modelRef.password.length >= value.length
    )
  }
  function validateConfirmPasswordSame (rule, value) {
    return value === verifyForm.value.password
  }

  const rules = {
    password: [
      {
        required: true,
        message: '请输入密码'
      }
    ],
    confirmPassword: [
      {
        required: true,
        message: '请再次输入密码'
      },
      {
        validator: validateConfirmPasswordStartWith,
        message: '两次密码输入不一致',
        trigger: 'input'
      },
      {
        validator: validateConfirmPasswordSame,
        message: '两次密码输入不一致',
        trigger: 'blur'
      }
    ]
  }

  /**
   * 如果没有激活码code和注册类型type则不允许在此页面停留
   */
  const timeout = ref(4000)
  const countdown = () => {
    if (timeout.value <= 0) {
      showDispatchModalRef.value = false
    } else {
      timeout.value -= 1000
      setTimeout(countdown, 1000)
    }
  }
  const showDispatchModal = () => {
    showDispatchModalRef.value = true
    timeout.value = 4000
    countdown()
  }
  if (!key || !type) {
    // 未从url中提取到激活码或注册类型就跳转到首页，不允许在此页面停留
    showDispatchModal()
  }


  // 提交注册请求到后端
  const handleRegister = (e: MouseEvent) => {
    registerLoading.value = true
    e.preventDefault()
    formRef.value?.validate((errors) => {
      if (errors) {
        registerLoading.value = false
        return
      }
      sendVerifyRequest()
    })
  }

  const sendVerifyRequest = async () => {
      // 字段认证通过，发送注册账号请求
      try {
        const { msg } = await nuxtApp.$request('/verify', {
          method:'POST',
          body: verifyForm.value,
          server: false,
          key:'register'
        })
        nuxtApp.$mutual.message.success(msg, {
          duration: 5000,
          onAfterLeave: () => {
            navigateTo('/')
          }
        })
      } catch (e) {
        nuxtApp.$mutual.message.error(e.message)
      } finally {
        registerLoading.value = false
      }
  }
</script>

<template>
  <n-form ref="formRef" :model="verifyForm" :rules="rules">
    <n-form-item path="password" label="密码">
      <n-input
        v-model:value="verifyForm.password"
        type="password"
        @keydown.enter.prevent
        placeholder="请输入密码"
      />
    </n-form-item>
    <n-form-item
      ref="rPasswordFormItemRef"
      first
      path="confirmPassword"
      label="重复密码"
    >
      <n-input
        v-model:value="verifyForm.confirmPassword"
        :disabled="!verifyForm.password"
        type="password"
        placeholder="请输入确认密码"
        @keydown.enter.prevent
      />
    </n-form-item>
    <n-row :gutter="[0, 24]">
      <n-col :span="24">
        <div style="display: flex; justify-content: flex-end">
          <n-button
            :disabled="verifyForm.key === null || verifyForm.confirmPassword === null
                      || verifyForm.password === null || verifyForm.type === null"
            round
            type="primary"
            @click="handleRegister"
            :loading="registerLoading">
            提交注册
          </n-button>
        </div>
      </n-col>
    </n-row>
  </n-form>

  <n-modal :show="showDispatchModalRef"
    :on-after-leave="() => navigateTo('/')">
    <n-card
      style="width: 600px"
      title="未检测到激活码，无法进行注册"
      size="huge"
      :bordered="false"
      role="dialog"
      aria-modal="true">
      在{{ timeout / 1000 }}秒后将回到首页，可点<NuxtLink to="/">回到首页</NuxtLink>直接离开
    </n-card>
  </n-modal>
</template>

<style scoped lang="scss">

</style>
